package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO search(LocalDate begin, LocalDate end) {
        // 订单状态为已完成的算一个营业额 status = 5
        // 拿到日期列表
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while(!begin.equals(end)){
            // 日期计算 ,begin 每次添加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 拿到营业额列表
        List<Double> turnoverlist = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 用map
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            // 拿到每一次的金额
            Double turnover = orderMapper.sumMount(map);
            // turnover为空的话就加入0.0
            turnover = turnover == null ? 0.0 : turnover;
            // 依次添加到集合里
            turnoverlist.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,",")) //将集合中的元素按指定分隔符拼接成!一个字符串
                .turnoverList(StringUtils.join(turnoverlist,","))
                .build();
    }

    /**
     * 统计用户数据
     * @return
     */

    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //拿到日期列表
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while(!begin.equals(end)){
            // 日期计算 ,begin 每次添加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 每天新增用户列表
        List<Integer> newUserList = new ArrayList<>();
        // 每天总用户列表
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("end",endTime);
            // 先查总的用户数量。
            Integer totalUser = userMapper.countByMap(map);
            // 在查新的用户数量。
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            // 依次添加到列表
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
    /**、
     * 统计指定时间的订单数据
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //拿到日期列表
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while(!begin.equals(end)){
            // 日期计算 ,begin 每次添加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天的订单总数——列表
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每天有效的订单数——列表
        List<Integer> validOrderCountList = new ArrayList<>();
        // 遍历日期集合
        for (LocalDate date : dateList) {
            // 查询每天的订单总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime,endTime,null);
            // 查询每天的有效订单数 status = 5
            Integer validOrderCount = getOrderCount(beginTime,endTime,Orders.COMPLETED);
            // 依次加入到列表
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        // 计算时间区间内的订单总数——对应的集合所有值相加
        Integer totalOrderCount = 0;
        for (Integer i : orderCountList) {
            totalOrderCount +=  i;
        }
        // 计算时间区间内的有效订单总数——对应的集合所有值相加
        Integer validOrderCount = 0;
        for (Integer i : validOrderCountList) {
            validOrderCount += i;
        }
        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        // 统计已完成的订单里的菜品和套餐销量
        // 查询orders 和 order_detail 表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 拿到销量前10的数据了——并且封装到一个集合里了。
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSaleTop10(beginTime,endTime);
        // 手动把List<GoodsSalesDTO>里的数据封装到SalesTop10ReportVO
        List<String> names = new ArrayList<>();
        List<String> numbers = new ArrayList<>();

        for (GoodsSalesDTO dto : salesTop10) {
            names.add(dto.getName());
            numbers.add(String.valueOf(dto.getNumber()));
        }
        // .join()集合/数组元素转换为字符串,使用指定分隔符连接元素,并且返回一个拼接后的字符串
        // 以下两个join()都一样
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(String.join(",", numbers))
                .build();
        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询数据库，拿到数据--获取最近30天的数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        // 获取概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(beginDate,LocalTime.MIN),LocalDateTime.of(endDate,LocalTime.MAX));
        // POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于in的模板创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取excel文件的Sheet页,拿第一个
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充数据-- 时间(给第二行的第二个空添加时间数据)
            sheet.getRow(1).getCell(1).setCellValue("时间："+beginDate+"至"+endDate);
            // 获取第四行
            XSSFRow row = sheet.getRow(3);
            // 给第四行的第3、5、7个空，依次添加数据
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            // 获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //填充明细数据
            for(int i = 0 ; i < 30 ; i++){
                // 每次时间加一
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));

                // 依次获取每一行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 封装好的条件调用统计订单数量
     * @param begin
     * @param end
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status", status);
        // 使用动态查询数量
        return orderMapper.countByMap(map);
    }
}
